/*
* Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* $Id: mainwindow.cpp 318 2009-02-22 20:35:11Z vjousse $
*/

#include "server.h"
#include "userinfo.h"
#include "mainwindow.h"
#include "application.h"
#include "connectdialog.h"
#include "channeldialog.h"
#include "controller.h"

#include "ircmodel.h"
#include <ircsession.h>

#include <QDesktopServices>
#include <QCloseEvent>
#include <QMessageBox>
#include <QWhatsThis>
#include <QSettings>
#include <QTimer>
#include <QUrl>

MainWindow* MainWindow::instance()
{
    static MainWindow window;
    return &window;
}

MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags)
    : QMainWindow(parent, flags), highlightTimer(0)
{
    ui.setupUi(this);
    
    QActionGroup* viewModeGroup = new QActionGroup(this);
    viewModeGroup->addAction(ui.actionTabsMode);
    viewModeGroup->addAction(ui.actionMdiMode);
    viewModeGroup->addAction(ui.actionSplitMode);

    ui.actionFindText->setShortcut(QKeySequence::Find);
    ui.actionFindNext->setShortcut(QKeySequence::FindNext);
    ui.actionFindPrevious->setShortcut(QKeySequence::FindPrevious);
    ui.actionWhatsThis->setShortcut(QKeySequence::WhatsThis);
    ui.menuView->addAction(ui.dockWidget->toggleViewAction());	
	ui.viewer->setTabsMode();
	/*
	QAction* action = new QAction(tr("TabMode"), this );

	action->setStatusTip( tr("Switch to tab mode") );

	connect( action, SIGNAL(triggered()), ui.viewer, SLOT(setTabsMode()) );
	
	ui.menuView->addAction(action);
	*/


    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(Application::windowIcon());
    trayIcon->setContextMenu(ui.menuFile);
    trayIcon->setVisible(true);
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
        this, SLOT(onIconActivated(QSystemTrayIcon::ActivationReason)));

//vj : TODO - make it works
/*
    connect(cApp, SIGNAL(currentConnectionChanged(Connection*)),
            this, SLOT(onCurrentConnectionChanged(Connection*)));
*/

    QSettings settings;
    QByteArray state = settings.value("window").toByteArray();
    restoreState(state);

    ServerList servers = settings.value("servers").value<ServerList>();
	
    foreach (Server server, servers)
        if (server.autoConnect)
            controller->connectTo(server);

    onHighlightRequested();


}

Viewer* MainWindow::viewer() const
{
    return ui.viewer;
}

QTreeView* MainWindow::viewTree() const
{
    return ui.treeView;
}

QListView* MainWindow::nickList() const
{
    return ui.listView;
}

void MainWindow::setController(Controller* aController) {
	controller=aController;
}

void MainWindow::closeEvent(QCloseEvent* event)
{
    if (!event->spontaneous())
    {
        // close action
        QString text = tr("Are you sure you want to quit?");
        if (QMessageBox::question(this, tr("Confirm"), text, QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
        {
            event->ignore();
        }
        else
        {
            QSettings settings;
            QByteArray state = saveState();
            settings.setValue("window", state);
        }
    }
    else
    {
        // close button
        hide();
        event->ignore();
    }
}

void MainWindow::on_actionConnect_triggered()
{
    ConnectDialog dialog(this);
    connect(&dialog, SIGNAL(connectRequested(Server)), controller, SLOT(onConnectRequested(Server)));
    dialog.exec();
}

void MainWindow::on_actionDisconnect_triggered()
{
    //Connection* connection = Application::currentConnection();
    //if (connection)
        //connection->disconnectFromServer();
}

void MainWindow::on_actionQuit_triggered()
{
    close();
}

void MainWindow::on_actionFindText_triggered()
{
}

void MainWindow::on_actionFindNext_triggered()
{
}

void MainWindow::on_actionFindPrevious_triggered()
{
}

void MainWindow::on_actionClearWindow_triggered()
{
}

void MainWindow::on_actionClearAllWindows_triggered()
{
}

void MainWindow::on_actionPreferences_triggered()
{
}

void MainWindow::on_actionWhatsThis_triggered()
{
    QWhatsThis::enterWhatsThisMode();
}

void MainWindow::on_actionReportBug_triggered()
{
    QDesktopServices::openUrl(QUrl(tr("http://code.google.com/p/communi/issues")));
}

void MainWindow::on_actionAboutCommuni_triggered()
{
    QMessageBox::about(this, QApplication::applicationName(), tr(
        "<h3>About Communi</h3>"
        "<a href='http://code.google.com/p/communi/'>http://code.google.com/p/communi/</a>"
        ));
}

void MainWindow::on_actionAboutQt_triggered()
{
    QMessageBox::aboutQt(this, QApplication::applicationName());
}

/*
void MainWindow::onCurrentConnectionChanged(Connection* connection)
{
    bool enabled = false;
    if (connection)
        enabled = connection->isConnected();
    ui.actionDisconnect->setEnabled(enabled);
}
*/

void MainWindow::onIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason)
    {
    case QSystemTrayIcon::DoubleClick:
        setVisible(!isVisible());
        break;
    case QSystemTrayIcon::Trigger:
        raise();
        activateWindow();
        break;
    default:
        break;
    }
}

void MainWindow::onHighlightRequested()
{
    if (!highlightTimer)
    {
        highlightTimer = new QTimer(this);
        connect(highlightTimer, SIGNAL(timeout()), this, SLOT(onHighlightRequested()));
    }

    if (isActiveWindow())
    {
        highlightTimer->stop();
        trayIcon->setIcon(Application::windowIcon());
    }
    else
    {
        if (!highlightTimer->isActive())
        {
            QApplication::alert(this);
            highlightTimer->start(500);
        }

        if (trayIcon->icon().isNull())
            trayIcon->setIcon(Application::windowIcon());
        else
            trayIcon->setIcon(QIcon());
    }
}

